from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session, joinedload
from app.database import get_db
from app.models.favorite import Favorite
from app.models.spot import Spot
from app.core.auth import get_current_user

router = APIRouter()

@router.get("")
def get_favorites(
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取用户的收藏列表"""
    favorites = (
        db.query(Favorite)
        .filter(Favorite.user_id == current_user.id)
        .join(Spot)
        .options(joinedload(Favorite.spot))
        .all()
    )
    
    return [
        {
            "id": fav.id,
            "spot": {
                "id": fav.spot.id,
                "name": fav.spot.name,
                "description": fav.spot.description,
                "price": fav.spot.price,
                "images": fav.spot.images,
                "type": fav.spot.type
            }
        }
        for fav in favorites
    ]

@router.post("/{spot_id}")
def add_favorite(
    spot_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """添加收藏"""
    # 检查景点是否存在
    spot = db.query(Spot).filter(Spot.id == spot_id).first()
    if not spot:
        raise HTTPException(status_code=404, detail="景点不存在")
    
    # 检查是否已经收藏
    existing = (
        db.query(Favorite)
        .filter(
            Favorite.user_id == current_user.id,
            Favorite.spot_id == spot_id
        )
        .first()
    )
    if existing:
        raise HTTPException(status_code=400, detail="已经收藏过了")
    
    # 创建收藏
    favorite = Favorite(user_id=current_user.id, spot_id=spot_id)
    db.add(favorite)
    db.commit()
    db.refresh(favorite)
    
    return {"message": "收藏成功"}

@router.delete("/{spot_id}")
def remove_favorite(
    spot_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """取消收藏"""
    favorite = (
        db.query(Favorite)
        .filter(
            Favorite.user_id == current_user.id,
            Favorite.spot_id == spot_id
        )
        .first()
    )
    
    if not favorite:
        raise HTTPException(status_code=404, detail="收藏不存在")
    
    db.delete(favorite)
    db.commit()
    
    return {"message": "取消收藏成功"} 